//
//  NetworkTool.m
//  封装AFN请求
//
//  Created by iMac_Kurt on 16/8/14.
//  Copyright © 2016年 Kurt_Qi. All rights reserved.
//

#import "NetworkTool.h"
#import "QKUserAccountViewModel.h"

/// NetworkToolProtocol:此协议中的方法为AFN私有方法
@protocol NetworkToolProtocol <NSObject>

- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;

@end
// 遵守协议，欺骗Xcode编译器，出现智能提示
@interface NetworkTool () <NetworkToolProtocol>

// token字典
@property (nonatomic, strong) NSMutableDictionary *tokenDict;

@end

@implementation NetworkTool

/// 创建一个业务类单例的方法
///
/// @return  NetworkTool
+ (instancetype)sharedTools {
    
    static NetworkTool *tool;
    
    static dispatch_once_t token;
    
    dispatch_once(&token, ^{
        // 注意：末尾需要包含 '/'
        NSURL *url = [NSURL URLWithString:@"http://httpbin.org/"];
        
        tool = [[self alloc] initWithBaseURL:url];
        
        // 设置反序列化格式
        tool.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    });
    
    return tool;
}

// 包装accessToken字典
- (NSMutableDictionary *)tokenDict {
    return [NSMutableDictionary dictionaryWithObject:[QKUserAccountViewModel sharedUserAccount].accessToken forKey:@"access_token"];
}

#pragma mark - 获取微博数据
- (void)getStatusData:(void(^)(id result, NSError *error))finished {
    // 准备参数
    NSString *urlStr = @"https://api.weibo.com/2/statuses/home_timeline.json";
    NSDictionary *params = self.tokenDict;
    // 请求数据
    [self request:GET URLString:urlStr parameters:params result:^(id result, NSError *error) {
        if (error != nil) {
            NSLog(@"请求网络数据出错");
            finished(nil, error);
        }else {
            finished(result, nil);
        }
    }];
}

#pragma mark - 获取用户信息
- (void)getUserInfoWithUid:(NSString *)uid finished:(void(^)(id result, NSError *error))finished {
    NSString *urlStr = @"https://api.weibo.com/2/users/show.json";
    
    NSMutableDictionary *params = self.tokenDict;
    params[@"uid"] = uid;
    
    [self request:GET URLString:urlStr parameters:params result:finished];
}

#pragma mark - OAuth相关
// Swift中的计算型属性相当于OC中的readonly属性，没有setter，只有getter，也没有带_的属性
- (NSURL *)oauthURL {
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat: @"https:api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@", client_id, redirect_uri]];
    return url;
}

/// 获取AccessToken
///
/// @param code     token授权码
/// @param finished 回调
- (void)loadAccessTokenWithCode:(NSString *)code finished:(void(^)(id result, NSError *error))finished {
    NSString *urlString = @"https://api.weibo.com/oauth2/access_token";
    NSDictionary *params = @{@"client_id": client_id,
                             @"client_secret": client_secret,
                             @"grant_type": grant_type,
                             @"code": code,
                             @"redirect_uri": redirect_uri};
    
    [self request:POST URLString:urlString parameters:params result:finished];
}

#pragma mark - 网络请求
/// 发送网络请求
///
/// @param URLString URLString
/// @param params    params
/// @param result    result 
- (void)request:(QKNetworkRequestMethod)method URLString:(NSString *)URLString parameters:(id)params result:(void (^)(id result, NSError *error))result {
    
    NSString *methodName = (method == GET) ? @"GET" : @"POST";
    // AFN发送GET和POST请求的方法内部调用此方法dataTaskWithHTTPMethod，区别只有请求方式method不同
    // 但是此方法是AFN私有的（只在.m文件中有实现），通过定义一个协议来调用此方法（OC黑魔法）
    [[self dataTaskWithHTTPMethod:methodName URLString:URLString parameters:params uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        result(responseObject, nil);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        result(nil, error);
        // 如果发生错误，不要提示给用户，但是必须打印知道是什么错误
        NSLog(@"%@",error);
    }] resume];
    
//    if (method == GET) {
//        [self GET:URLString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            result(responseObject, nil);
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            result(nil, error);
//        }];
//    }else {
//        [self POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            result(responseObject, nil);
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            result(nil, error);
//        }];
//    }
}

@end
